import { sendInternalMessage } from '@/api/user'

/**
 * 通知服务 - 用于管理餐饮提醒和其他通知
 */
class NotificationService {
  constructor () {
    this.notifications = []
    this.messageQueue = []
  }

  /**
   * 发送餐饮提醒消息
   * @param {Object} meal - 餐饮对象
   * @param {string} mealTypeLabel - 餐次标签
   */
  async sendMealReminder (meal, mealTypeLabel) {
    try {
      const message = {
        title: `${mealTypeLabel}提醒`,
        content: `现在是${mealTypeLabel}时间！建议您享用：${meal.foodName}（${meal.portion}g，${meal.calories}kcal）`,
        type: 'meal_reminder',
        icon: this.getMealIcon(meal.mealType),
        priority: 'high',
        metadata: {
          mealId: meal.id,
          mealType: meal.mealType,
          foodName: meal.foodName,
          calories: meal.calories,
          protein: meal.protein,
          fat: meal.fat,
          carbs: meal.carbs,
          cookingMethod: meal.cookingMethod
        }
      }

      // 调用API发送站内信
      await sendInternalMessage(message)
      console.log('餐饮提醒消息已发送:', message)
      return true
    } catch (error) {
      console.error('发送餐饮提醒失败:', error)
      return false
    }
  }

  /**
   * 发送营养提醒
   * @param {Object} nutritionStats - 营养统计
   */
  async sendNutritionReminder (nutritionStats) {
    try {
      const recommendedCalories = 2000
      const calorieRatio = (nutritionStats.calories / recommendedCalories * 100).toFixed(1)

      let contentMessage = `今日摄入：${nutritionStats.calories}kcal（建议${recommendedCalories}kcal）`

      // 根据摄入情况提供建议
      if (nutritionStats.calories < recommendedCalories * 0.7) {
        contentMessage += '，摄入不足，需要增加进食。'
      } else if (nutritionStats.calories > recommendedCalories * 1.3) {
        contentMessage += '，摄入过多，建议适量减少。'
      }

      const message = {
        title: '营养摄入提醒',
        content: contentMessage,
        type: 'nutrition_reminder',
        icon: 'md-nutrition',
        priority: 'normal',
        metadata: {
          calories: nutritionStats.calories,
          protein: nutritionStats.protein,
          fat: nutritionStats.fat,
          carbs: nutritionStats.carbs,
          calorieRatio
        }
      }

      await sendInternalMessage(message)
      console.log('营养提醒消息已发送:', message)
      return true
    } catch (error) {
      console.error('发送营养提醒失败:', error)
      return false
    }
  }

  /**
   * 发送计划提醒
   * @param {string} title - 标题
   * @param {string} content - 内容
   * @param {Object} metadata - 元数据
   */
  async sendPlanReminder (title, content, metadata = {}) {
    try {
      const message = {
        title,
        content,
        type: 'plan_reminder',
        priority: 'normal',
        metadata
      }

      await sendInternalMessage(message)
      console.log('计划提醒消息已发送:', message)
      return true
    } catch (error) {
      console.error('发送计划提醒失败:', error)
      return false
    }
  }

  /**
   * 获取餐饮类型的图标
   * @param {string} mealType - 餐次类型
   */
  getMealIcon (mealType) {
    const iconMap = {
      breakfast: 'md-sunny',
      lunch: 'md-flame',
      dinner: 'md-moon'
    }
    return iconMap[mealType] || 'md-restaurant'
  }

  /**
   * 批量发送提醒
   * @param {Array} messages - 消息数组
   */
  async sendBatchMessages (messages) {
    try {
      const results = await Promise.allSettled(
        messages.map(msg => sendInternalMessage(msg))
      )
      const succeeded = results.filter(r => r.status === 'fulfilled').length
      console.log(`批量发送消息完成，成功: ${succeeded}/${messages.length}`)
      return succeeded === messages.length
    } catch (error) {
      console.error('批量发送消息失败:', error)
      return false
    }
  }

  /**
   * 队列消息（用于离线或延迟发送）
   * @param {Object} message - 消息对象
   */
  queueMessage (message) {
    message.queuedAt = new Date()
    this.messageQueue.push(message)
    console.log('消息已加入队列:', message)
  }

  /**
   * 发送所有队列中的消息
   */
  async flushMessageQueue () {
    if (this.messageQueue.length === 0) {
      return true
    }

    try {
      const messages = [...this.messageQueue]
      this.messageQueue = []
      await this.sendBatchMessages(messages)
      return true
    } catch (error) {
      console.error('发送消息队列失败:', error)
      return false
    }
  }

  /**
   * 清空消息队列
   */
  clearMessageQueue () {
    this.messageQueue = []
    console.log('消息队列已清空')
  }

  /**
   * 获取消息队列长度
   */
  getQueueLength () {
    return this.messageQueue.length
  }
}

// 创建单例实例
const notificationService = new NotificationService()

export default notificationService
